#include "Timer_key.h"


static const char* TAG = "timer";


esp_timer_handle_t Onectimer;
esp_timer_handle_t Periodictimer;

extern uint32_t longPressTime;
extern bool release_key_flag;
uint8_t pressTime = 0;


static void IRAM_ATTR gpio_isr_handler(void* arg);
static void periodic_timer_callback(void* arg);
static void once_timer_callback(void* arg);




static void IRAM_ATTR gpio_isr_handler(void* arg)
{   
   
    start_onece_key_timer();
    
    //pressTime ++;

}

static void periodic_timer_callback(void* arg)
{
    int64_t time_since_boot = esp_timer_get_time();
    ESP_LOGI(TAG, "Periodic timer called, time since boot: %lld us", time_since_boot);
}

//单按一次按键增加一次led灯的亮度
static void keySetLEDBreathness(void)
{
    static uint8_t breath_level = 0;
    if(pressTime == 1)
    {
        breath_level ++;
        setLEDBrightness(breath_level);
        if(breath_level >= 6)
        {
            breath_level = 0;
            setLEDBrightness(breath_level);
        }
    }
}

static void once_timer_callback(void* arg)
{
    // int64_t time_since_boot = esp_timer_get_time();
    // ESP_LOGI(TAG, "Once timer called, time since boot: %lld us", time_since_boot);
    if((longPressTime <= 100) && (pressTime != 0))
    {
        if (release_key_flag == true)
        {
            ESP_LOGI(TAG,"the pressTime is %d \r\n",pressTime);
            keySetLEDBreathness();
        }
        
    }

    
    pressTime = 0;
}

void button_init(void)
{
    gpio_config_t io_conf;
    io_conf.intr_type = GPIO_INTR_POSEDGE;
    io_conf.pin_bit_mask = GPIO_INPUT_PIN_SEL;
    io_conf.mode = GPIO_MODE_INPUT;
    io_conf.pull_up_en = 1;
    gpio_config(&io_conf);

    gpio_install_isr_service(ESP_INTR_FLAG_DEFAULT);
    gpio_isr_handler_add(GPIO_INPUT_IO_0, gpio_isr_handler, (void*) GPIO_INPUT_IO_0);
}

void periodic_timer_init(void)
{
    const esp_timer_create_args_t periodic_timer_args = {
            .callback = &periodic_timer_callback,
            .name = "periodic"
    };

    esp_timer_create(&periodic_timer_args, &Periodictimer);
    esp_timer_start_periodic(Periodictimer, 3*1000*1000);
    ESP_LOGI(TAG, "Started Periodic timers, time since boot: %lld us", esp_timer_get_time());
}

void once_timer_init(void)
{

    
    const esp_timer_create_args_t once_timer_args = {
            .callback = &once_timer_callback,
            .name = "once"
    };

    esp_timer_create(&once_timer_args, &Onectimer);
    // esp_timer_start_once(timer, 2*1000*1000);
    // ESP_LOGI(TAG, "Started Once timers, time since boot: %lld us", esp_timer_get_time());
}



void start_onece_key_timer(void)
{
    
    esp_err_t timerStatus = esp_timer_start_once(Onectimer, 0.5*1000*1000);

    if(timerStatus !=  ESP_OK)
    {
        esp_timer_stop(Onectimer);
        esp_timer_start_once(Onectimer, 0.5*1000*1000);
    }
}